﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Http;
using System.Web.Routing;
using Top.Web.Api;
using Top.PointStore.Business;
using Top.PointStore.LuckTurntable;
using Top.Web;
using Top.Web.Api.Filters;
//using Top.PointStore.Filters;

namespace Top.PointStore
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : HttpApplication
    {
        private static bool isFirstStart = true; 
        protected void Application_Start()
        {
            //ApiConfig.AddRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "{controller}/{action}",
            //    defaults: new { action = "Get" }
            //);
            ApiConfig.AddFilter(new UrlReferrerAttribute("tops001.com", "apitops.com"));
            if (isFirstStart)
            {
                isFirstStart = false;
                var task = new Task(() =>
                {
                    MemoryTable.Init();
                    LuckBigWheel.Init();
                });
                task.Start();
            }            
            RegisterCacheEntry();
        }

        //private const string DummyPageUrl = "http://point.beta.apitops.com/demo/Lasting";
        private const string DummyPageUrl = "http://api.point.apitops.com/demo/Lasting";
        private const string DummyCacheItemKey = "KaKaoPointStore";

        // 注册一缓存条目在10分钟内到期，到期后触发的调事件  
        private void RegisterCacheEntry()
        {
            if (null != HttpContext.Current.Cache[DummyCacheItemKey]) return;
            HttpContext.Current.Cache.Add(
                DummyCacheItemKey,
                "Lasting",
                null,
                DateTime.MaxValue, TimeSpan.FromMinutes(15),
                CacheItemPriority.NotRemovable,
                new CacheItemRemovedCallback(CacheItemRemovedCallback)
                );
        }

        // 缓存项过期时程序模拟点击页面，阻止应用程序结束  
        public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            if (DateTime.Now.Hour>=2&&DateTime.Now.Hour<5)
            {
                return;
            }
            HitPage();
        }

        // 模拟点击网站网页  
        private void HitPage()
        {
            System.Net.WebClient client = new System.Net.WebClient();
            client.DownloadData(DummyPageUrl);
        }
        protected void Application_BeginRequest(Object sender, EventArgs e)
        {
            if (HttpContext.Current.Request.Url.ToString() == DummyPageUrl)
            {
                RegisterCacheEntry();
            }
        }

    }
}